<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Countdown</title>
</head>

<body>
  <p>思考怎么做本地缓存</p>
  <p>1. 每次刷新后重新计时，连续刷新会导致时间停滞</p>
  <p>2. 计时未完成离开页面，很久之后再登入依然计时</p>
  <div id="container">
    <input id="input" />
    <button id="button">获取验证码</button>
  </div>

  <style>
    :root {
      --primary: dodgerblue;
    }

    #container {
      margin-top: 240px;
      height: 240px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: #ccc 1px solid;
      text-align: center;
    }


    #input,
    #button {
      margin: 0 4px;
      padding: 8px;
      border-radius: 4px;
      border: #ccc 1px solid;
    }

    #input:hover,
    #button:hover {
      border: var(--primary) 1px solid;
      cursor: pointer;
    }
  </style>

  <script>
    // 倒计时
    const SECONDS = 6;

    const dom = {
      container: document.querySelector("#container"),
      input: document.querySelector("#input"),
      button: document.querySelector("#button"),
    }

    window.addEventListener("load", resume);
    dom.button.addEventListener("click", () => countDown());

    function resume() {
      let remainder = get();
      if (remainder > 0 && remainder < SECONDS) {
        countDown(remainder);
      }
    }

    function countDown(seconds = SECONDS) {
      let timer = null;
      function check(s) {
        if (s === 0) {
          clearTimeout(timer); timer = null;
          recover();
          return;
        }

        update(s);
        set(s - 1);
        timer = setTimeout(check, 1000, s - 1);
      }
      update(seconds);
      timer = setTimeout(check, 1000, seconds - 1);
    }

    function recover() {
      dom.button.textContent = `获取验证码`;
      dom.button.removeAttribute("disabled");
      set(SECONDS);
    }
    function update(s) {
      dom.button.textContent = `已发送(${s}秒后重试)`;
      dom.button.setAttribute("disabled", "disabled");
    }
    function set(s = 0) {
      localStorage.setItem('__seconds', s);
    }
    function get() {
      let s = +localStorage.getItem('__seconds');
      if (Number.isInteger(s)) return s;
      return -1;
    }
  </script>
</body>

</html>